<template>
  <div class="assignment-area">
    <!-- 作业栏标题 -->
    <h2 class="title">作业栏</h2>

    <!-- 作业表格 -->
    <div class="assignment-table">
      <el-table :data="tableData" stripe>
        <el-table-column label="学生" prop="name" />
        <el-table-column label="学号" prop="id" />
        <el-table-column label="提交日期" prop="date" />
        <el-table-column label="文件" prop="file">
          <!-- 添加下载按钮 -->
          <template #default="scope">
            <div>
              <span>{{ scope.row.file }}</span>
              <el-button
                type="danger"
                plain
                class="download-button"
                @click="handleDownload(scope.row.studentHomeworkId)"
              >
                下载
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="分数">
          <template #default="scope">
            <div>
              <el-input
                v-model="scope.row.score"
                placeholder="输入分数"
                type="number"
              ></el-input>
              <el-button
                type="primary"
                plain
                class="upload-button"
                @click="handleScoreSubmit(scope.row.studentHomeworkId, scope.row.score)"
              >
                提交
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router/composables';

const route = useRoute();

const tableData = ref([]); // 初始化为空数组

// 获取作业数据的函数
const fetchTableData = async (homeworkId) => {
  try {
    const response = await axios.get('/homework/teacherviewhomework', {
      params: { homeworkId }
    });
    tableData.value = response.data.map(item => ({
      studentHomeworkId: item.studentHomeworkId,
      name: item.userName, // 使用 userName 字段作为学生姓名
      id: item.userId,     // 使用 userId 字段作为学号
      date: item.submissionTime, // 提交日期
      file: item.fileName,  // 文件名
      score: item.score || '' // 初始分数
    }));
  } catch (error) {
    console.error('获取作业数据失败:', error);
  }
};

// 处理下载按钮点击
const handleDownload = async (studentHomeworkId) => {
  try {
    const response = await axios.get('/homework/downloadhomework', {
      params: { studentHomeworkId },
      responseType: 'blob' // 确保返回的是文件流
    });

    // 创建 URL 并触发下载
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `作业_${studentHomeworkId}.pdf`); // 设置默认文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url); // 清理 URL

  } catch (error) {
    console.error('下载文件失败:', error);
  }
};

// 提交分数的函数
const handleScoreSubmit = async (studentHomeworkId, score) => {
  
  try {
    const formData=new FormData()
    formData.append("studentHomeworkId",studentHomeworkId);
    formData.append("score",parseInt(score, 10))
    await axios.post('/homework/scoringhomework', formData);
    console.log(`学生 ${studentHomeworkId} 的分数已提交为 ${score}`);
  } catch (error) {
    console.error('提交分数失败:', error);
  }
};

// 在组件挂载后获取数据
onMounted(() => {
  const homeworkId = route.params.homeworkId; // 从路由参数中获取 homeworkId
  fetchTableData(homeworkId);
});
</script>

<style scoped>
.assignment-area {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}

.title {
  font-size: 50px;
  font-weight: bold;
  margin-bottom: 20px;
}

.assignment-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ddd;
  padding: 10px;
  border-radius: 8px;
  background-color: #f9f9f9;
}

/* 自定义下载按钮样式 */
.download-button {
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

/* 自定义上传按钮样式 */
.upload-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}
</style>
